package com.wjm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.wjm.annotation.LoginValidate;
import com.wjm.entity.Student;
import com.wjm.util.PropertiesUtil;
import com.wjm.util.StringUtil;

public class ClientLoginInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean result = false;
		HttpSession session = request.getSession();
		if (session.getAttribute(StringUtil.WEB_ROOT_KEY_SESS) == null) {
			session.setAttribute(StringUtil.WEB_ROOT_KEY_SESS, PropertiesUtil.getValue(StringUtil.WEB_ROOT_KEY));
		}
		if (handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			LoginValidate annotation = method.getMethod().getAnnotation(LoginValidate.class);
			if (annotation == null || annotation.needLogin() == true) {
				Student stu = (Student) request.getSession().getAttribute(StringUtil.STUDENT_KEY);
				if (stu != null) {
					result = true;
				} else {
					response.sendRedirect(session.getAttribute(StringUtil.WEB_ROOT_KEY_SESS) + "client/stu/login");
				}
			} else {
				result = true;
			}
		}
		return result;
	}
}
